# -*- coding: utf-8 -*-

from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from lxml import etree
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import time
from fake_useragent import UserAgent


"""
facebook
18241255868,gkx55868
79172462892,JgqUsVNmg9
获取friends
"""

# 初始化
def init_driver(url):
    firefox_options = Options()
    # fire_options.add_argument('--headless') # 无头模式
    firefox_options.add_argument('--disable-gpu')
    firefox_options.set_preference("general.useragent.override", 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36')  # 修改请求头，伪装浏览器型号
    # driver = webdriver.Chrome(chrome_options=chrome_options) # 已经设置PATH环境变量
    # 未在PATH环境变量中设置，需要设置驱动可执行路径
    driver = webdriver.Firefox(executable_path='D:\\webdriver\\geckodriver.exe', options=firefox_options)
    driver.maximize_window()  # 浏览器最大化
    driver.get(url)
    return driver

def login(drive):
    # 设置等待
    wait = WebDriverWait(driver, 10)
    driver.find_element_by_id('email').send_keys("18241255868")
    driver.find_element_by_id('pass').send_keys("gkx55868")
    try:
        driver.find_element_by_id('loginbutton').click()
    except:
        driver.find_element_by_name('login').click()
    return driver

# 获取页面url
def get_url(drive):
    driver.get("https://www.facebook.com/vladislav.ladygin?fref=pymk_rhc")
    time.sleep(1)
    driver.find_element_by_id('findFriendsNav').click()
    time.sleep(1)
    while True:
        page_height = driver.execute_script('return document.documentElement.scrollHeight')
        driver.execute_script(f"window.scrollBy(0, {page_height})")
        time.sleep(1)
        html = etree.HTML(driver.page_source)
        for t in html.xpath('//li[@class="friendBrowserListUnit"]'):
            urlChild = t.xpath('./div/a/@href')[0]
            username = t.xpath('./div/div/div/div/div/div/div/a/text()')[0]
            print("=================")
            print(urlChild)
            print(username)






def close_driver(driver):
    driver.quit()


if __name__ == '__main__':
    url = "https://www.facebook.com/"
    driver = init_driver(url)
    login(driver)
    get_url(driver)
